<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>
	<meta http-equiv="content-type" content="text/html;charset=utf-8">
	<link rel="stylesheet" href="/SimpleBlog/css/default.css" type="text/css" />
	<title>小博客</title>
</head>
<body>

<?php
require_once 'functions.inc.php';
require_once 'db.inc.php';
require_once 'images.inc.php';
require_once 'comments.inc.php';

// var_dump($_POST);
// var_dump($_FILES);
// var_dump($_SERVER);

session_start();

if ($_SERVER["REQUEST_METHOD"] == "GET" &&
	isset($_GET["action"]) &&
	$_GET["action"] == "comment_delete") {
	$com = new Comments();
	echo $com->confirm_delete($_GET["id"]);
	exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST" &&
	isset($_POST["action"]) &&
	$_POST["action"] == "comment_delete") {
	$loc = $_POST["url"];
	if ($_POST["confirm"] == "是") {
		$com = new Comments();
		if ($com->delete_comment($_POST["id"]))
			redirect($loc, "删除成功！");
		else
			redirect($loc, "删除失败！");
	} else {
		redirect($loc, "删除已取消。");
	}
	exit();
}

// 处理评论
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
	$_POST["submit"] == "发表评论") {
	require_once 'comments.inc.php';
	$comment = new Comments();
	$result = $comment->save_comment($_POST);
	if ($result) {
		if (isset($_SERVER["HTTP_REFERER"])) {
			redirect($_SERVER["HTTP_REFERER"], "评论成功！");
		} else {
			redirect("/SimpleBlog/index.php", "评论成功！");
		}
	} else {
		redirect("/SimpleBlog/index.php", "评论失败，返回首页！");
	}
	exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST" &&
	isset($_POST["action"]) &&
	$_POST["action"] == "createuser") {
	if ($_POST["submit"] == "创建") {
		$user = $_POST["username"];
		$pwd = $_POST["password"];
		if (empty($user) || empty($pwd) || strlen($pwd) < 6) {
			redirect("/SimpleBlog/admin/createuser", "请输入用户名及大于6位的密码！");
		}
		$salt = substr($pwd, 0, 3);
		$enc = crypt($pwd, $salt);
		$link = new PDO(DB_INFO, DB_USERNAME, DB_PASSWORD);
		$sql = "INSERT INTO admin (name, password) VALUES (?, ?)";
		$stmt = $link->prepare($sql);
		if ($stmt && $stmt->execute(array($user, $enc))) {
			redirect("/SimpleBlog/", "注册成功！");
		} else {
			redirect("/SimpleBlog/admin/createuser", "注册失败！");
		}
	} else {
		redirect("/SimpleBlog/admin/createuser", "注册取消！");
	}
	exit();
}

if ($_SERVER["REQUEST_METHOD"] == "GET" &&
	isset($_GET["action"]) &&
	$_GET["action"] == "logout") {
	session_destroy();
	redirect("/SimpleBlog", "您已经注销。");
	exit(0);
}

if ($_SERVER["REQUEST_METHOD"] == "POST" &&
	isset($_POST["action"]) &&
	$_POST["action"] == "login") {
	if ($_POST["submit"] == "登录") {
		if (!(isset($_SESSION["verify"]) &&
			isset($_POST["verify"]) &&
			$_SESSION["verify"] == $_POST["verify"])) {
			redirect($_SERVER["HTTP_REFERER"], "验证码错误！");
			exit();
		}
		unset($_SESSION["verify"]);
	 	$user = $_POST["username"];
	 	$pwd = $_POST["password"];
	 	if (empty($user) || empty($pwd) || strlen($pwd) < 6) {
	 		redirect($_SERVER["HTTP_REFERER"],
	 			"请输入用户名及大于6位的密码！");
	 		exit();
	 	}
	 	$salt = substr($pwd, 0, 2);
	 	$pwd = crypt($pwd, $salt);
		$link = new PDO(DB_INFO, DB_USERNAME, DB_PASSWORD);
		$sql = "SELECT password FROM admin WHERE name=?";
		$stmt = $link->prepare($sql);
		if ($stmt && $stmt->execute(array($user))) {
			$arr = $stmt->fetch();
			if (isset($arr["password"]) && $arr["password"] == $pwd) {
				$_SESSION["loggedin"] = 1;
				redirect("/SimpleBlog/", "登录成功！");
			} else {
				redirect($_SERVER["HTTP_REFERER"],
					"用户名或密码错误");
			}
		} else {
			redirect($_SERVER["HTTP_REFERER"], "登录失败！");
		}
	}
	exit();
}

//  POST 请求, 且点击了提交按钮, 且标题和内容都非空
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
	$_POST["submit"] == "提交" &&
	($title = $_POST["title"]) &&
	($entry = $_POST["entry"]) &&
    ($page = $_POST["page"])) {
	try {
		$link = new PDO(DB_INFO, DB_USERNAME, DB_PASSWORD);
	} catch (PDOException $e) {
		$msg = "数据连接错误：".$e->getMessage();
		redirect("/SimpleBlog/admin/$page", $msg);
	}
	$url = make_url($title);
	// 处理上传图片
	$handler = new ImageHandler("/SimpleBlog/images");
	if (!empty($_FILES['image']['tmp_name'])) {
		try {
			$img_path = $handler->process_uploaded($_FILES["image"]);
		} catch (Exception $e) {
			die($e->getMessage());
		}
	} else {
		$img_path = NULL;
	}

	if (strlen($_POST["id"])) {
		$sql = "UPDATE entries SET title=?,image=?,entry=?,url=? WHERE id=? LIMIT 1";
		$stmt = $link->prepare($sql);
		$stmt->execute(array($title, $img_path, $entry, $url, $_POST["id"]));
		$msg = "编辑文章成功!";
	} else {
		$sql = "INSERT INTO entries (url, title, image, entry, page) VALUES (?, ?, ?, ?, ?)";
		$stmt = $link->prepare($sql);
		$stmt->execute(array($url, $title, $img_path, $entry, $page));
		$stmt->closeCursor();
		$msg = "发表文章成功!";
	}
	$page = htmlentities(strip_tags($page));
	// 采用编码后的 URL 送入数据库
	// 跳转时的第一次编码用于搞定 JS
	// 第二次编码用于搞定 Apache
	redirect("/SimpleBlog/$page/".urlencode(urlencode($url)), $msg);
} else {
	redirect("../admin.php?page=$page", "发表文章失败。");
}

?>

</body>
</html>